<template>
  <div class="system">
    <h1 class="page-title">系统管理</h1>
    
    <el-tabs type="border-card">
      <!-- 用户管理 -->
      <el-tab-pane label="用户管理">
        <div class="tab-header">
          <el-button type="primary" @click="openUserDialog(null)">
            <el-icon><Plus /></el-icon> 新建用户
          </el-button>
        </div>
        
        <el-table :data="userList" stripe>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column prop="role" label="角色" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.role === 1 ? 'danger' : 'primary'">
                {{ scope.row.role === 1 ? '管理员' : '运维人员' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="updateStatus(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="openUserDialog(scope.row)">
                编辑
              </el-button>
              <el-button type="warning" size="small" @click="resetPassword(scope.row)">
                重置密码
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      
      <!-- 系统配置 -->
      <el-tab-pane label="系统配置">
        <el-form :model="configForm" label-width="150px" style="max-width: 600px">
          <el-form-item label="日志保留期（天）">
            <el-input-number v-model="configForm.logRetentionDays" :min="1" :max="365" />
          </el-form-item>
          <el-form-item label="缓存过期时间（小时）">
            <el-input-number v-model="configForm.cacheExpireHours" :min="1" :max="72" />
          </el-form-item>
          <el-form-item label="告警邮件通知">
            <el-switch v-model="configForm.emailNotification" />
          </el-form-item>
          <el-form-item label="自动清理日志">
            <el-switch v-model="configForm.autoCleanLog" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveConfig" :loading="configLoading">保存配置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      <!-- 操作日志 -->
      <el-tab-pane label="操作日志">
        <el-table :data="opLogList" stripe v-loading="opLogLoading">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="操作用户" width="150" />
          <el-table-column prop="opType" label="操作类型" width="120">
            <template #default="scope">
              <el-tag :type="getOpTypeColor(scope.row.opType)">
                {{ getOpTypeName(scope.row.opType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="opDesc" label="操作描述" show-overflow-tooltip />
          <el-table-column prop="ip" label="IP地址" width="150" />
          <el-table-column prop="opTime" label="操作时间" width="180" />
        </el-table>
        
        <!-- 空状态 -->
        <el-empty
          v-if="!opLogLoading && opLogList.length === 0"
          description="暂无操作日志"
        />
      </el-tab-pane>
    </el-tabs>
    
    <!-- 用户对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="userForm.id ? '编辑用户' : '新建用户'"
      width="500px"
    >
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="密码" v-if="!userForm.id">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="角色">
          <el-radio-group v-model="userForm.role">
            <el-radio :label="1">管理员</el-radio>
            <el-radio :label="2">运维人员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUser">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getUserList, createUser, updateUserStatus, resetPassword as resetPwd } from '@/api/user'
import { getSysConfigList, batchUpdateSysConfig } from '@/api/sysConfig'
import { getOpLogList } from '@/api/opLog'
import { ElMessage } from 'element-plus'

const userList = ref([])
const opLogList = ref([])
const userDialogVisible = ref(false)
const configLoading = ref(false)
const configList = ref([]) // 存储原始配置列表
const opLogLoading = ref(false)

const userForm = reactive({
  id: null,
  username: '',
  password: '',
  email: '',
  role: 2
})

const configForm = reactive({
  logRetentionDays: 30,
  cacheExpireHours: 48,
  emailNotification: true,
  autoCleanLog: true
})

const loadUsers = async () => {
  try {
    const res = await getUserList()
    if (res.code === 200) {
      userList.value = res.data || []
    } else {
      userList.value = []
    }
  } catch (error) {
    userList.value = []
    console.error('加载用户失败', error)
  }
}

const openUserDialog = (user) => {
  if (user) {
    Object.assign(userForm, user)
  } else {
    userForm.id = null
    userForm.username = ''
    userForm.password = ''
    userForm.email = ''
    userForm.role = 2
  }
  userDialogVisible.value = true
}

const submitUser = async () => {
  try {
    const res = await createUser(userForm)
    if (res.code === 200) {
      ElMessage.success('保存成功')
      userDialogVisible.value = false
      loadUsers()
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const updateStatus = async (user) => {
  try {
    await updateUserStatus(user.id, user.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

const resetPassword = async (user) => {
  try {
    await resetPwd(user.id, '123456')
    ElMessage.success('密码已重置为 123456')
  } catch (error) {
    ElMessage.error('重置失败')
  }
}

// 加载系统配置
const loadConfig = async () => {
  try {
    const res = await getSysConfigList()
    if (res.code === 200 && res.data) {
      configList.value = res.data
      
      // 将配置映射到表单
      res.data.forEach(item => {
        if (item.configKey === 'log.retention.days') {
          configForm.logRetentionDays = parseInt(item.configValue)
        } else if (item.configKey === 'cache.expire.hours') {
          configForm.cacheExpireHours = parseInt(item.configValue)
        } else if (item.configKey === 'email.notification') {
          configForm.emailNotification = item.configValue === 'true'
        } else if (item.configKey === 'auto.clean.log') {
          configForm.autoCleanLog = item.configValue === 'true'
        }
      })
    }
  } catch (error) {
    console.error('加载系统配置失败', error)
  }
}

// 保存系统配置
const saveConfig = async () => {
  configLoading.value = true
  try {
    // 构建要更新的配置数组
    const updates = []
    
    configList.value.forEach(item => {
      let newValue = null
      
      if (item.configKey === 'log.retention.days') {
        newValue = String(configForm.logRetentionDays)
      } else if (item.configKey === 'cache.expire.hours') {
        newValue = String(configForm.cacheExpireHours)
      } else if (item.configKey === 'email.notification') {
        newValue = String(configForm.emailNotification)
      } else if (item.configKey === 'auto.clean.log') {
        newValue = String(configForm.autoCleanLog)
      }
      
      if (newValue !== null && newValue !== item.configValue) {
        updates.push({
          id: item.id,
          configKey: item.configKey,
          configValue: newValue,
          configType: item.configType,
          description: item.description
        })
      }
    })
    
    if (updates.length === 0) {
      ElMessage.info('配置未改变')
      return
    }
    
    const res = await batchUpdateSysConfig(updates)
    if (res.code === 200) {
      ElMessage.success('配置保存成功')
      loadConfig() // 重新加载配置
    } else {
      ElMessage.error(res.message || '配置保存失败')
    }
  } catch (error) {
    console.error('保存系统配置失败', error)
    ElMessage.error('配置保存失败')
  } finally {
    configLoading.value = false
  }
}

// 加载操作日志
const loadOpLogs = async () => {
  opLogLoading.value = true
  try {
    const res = await getOpLogList({ pageNum: 1, pageSize: 50 })
    if (res.code === 200) {
      opLogList.value = res.data.records || res.data.list || []
    } else {
      opLogList.value = []
    }
  } catch (error) {
    opLogList.value = []
    console.error('加载操作日志失败', error)
  } finally {
    opLogLoading.value = false
  }
}

// 操作类型映射
const getOpTypeName = (type) => {
  const typeMap = {
    'LOGIN': '登录',
    'LOGOUT': '退出',
    'CREATE': '创建',
    'UPDATE': '更新',
    'DELETE': '删除',
    'EXPORT': '导出',
    'QUERY': '查询'
  }
  return typeMap[type] || type
}

// 操作类型颜色
const getOpTypeColor = (type) => {
  const colorMap = {
    'LOGIN': 'success',
    'LOGOUT': 'info',
    'CREATE': 'primary',
    'UPDATE': 'warning',
    'DELETE': 'danger',
    'EXPORT': '',
    'QUERY': ''
  }
  return colorMap[type] || ''
}

onMounted(() => {
  loadUsers()
  loadConfig()
  loadOpLogs()
})
</script>

<style scoped lang="scss">
.system {
  .tab-header {
    margin-bottom: 20px;
  }
}
</style>

